// src/store/modules/contactList.js
import service from "../../utils/request";

const state = {
  // 加载状态
  loading: false,
  
  // 好友列表（私聊）
  friends: [],
  
  // 群组列表（群聊）
  groups: [],
  
  // 搜索关键词
  searchKeyword: "",
  
  // 当前选中的联系人
  currentId: null,
  currentType: null, // 'friend' 或 'group'
  
  // 在线状态
  onlineStatus: {},

  // 好友请求
  friendRequests: {
    sent: [],
    received: [],
  },

  // 黑名单
  blacklist: [],

  // 置顶联系人
  pinnedFriends: [],
  pinnedGroups: [],

  // 免打扰设置
  muteSettings: {},

  // 排序设置
  sortBy: "name", // name, onlineStatus, lastSeen
  sortOrder: "asc", // asc, desc

  // 过滤设置
  filterType: "all", // all, friends, groups, online, offline, blocked
  
  // 统计信息
  statistics: {
    totalFriends: 0,
    totalGroups: 0,
    onlineFriends: 0,
    activeGroups: 0
  }
};

const mutations = {
  // 加载状态
  SET_LOADING(state, loading) {
    state.loading = loading;
  },
  
  // 别名
  setLoading(state, loading) {
    state.loading = loading;
  },
  
  // 基础操作 - 好友列表
  SET_FRIENDS(state, friends) {
    state.friends = friends;
  },

  ADD_FRIEND(state, friend) {
    state.friends.push(friend);
  },

  UPDATE_FRIEND(state, { id, updates }) {
    const index = state.friends.findIndex((friend) => friend.id === id);
    if (index !== -1) {
      state.friends[index] = { ...state.friends[index], ...updates };
    }
  },

  // 基础操作 - 群组列表
  SET_GROUPS(state, groups) {
    state.groups = groups;
  },

  ADD_GROUP(state, group) {
    state.groups.push(group);
  },

  UPDATE_GROUP(state, { id, updates }) {
    const index = state.groups.findIndex((group) => group.id === id);
    if (index !== -1) {
      state.groups[index] = { ...state.groups[index], ...updates };
    }
  },

  // 统计信息
  SET_STATISTICS(state, statistics) {
    state.statistics = { ...state.statistics, ...statistics };
  },

  // 更新好友在线状态
  UPDATE_FRIEND_STATUS(state, { friendId, isActive }) {
    state.friends.forEach(group => {
      if (group.friendshipsDTOS) {
        group.friendshipsDTOS.forEach(friend => {
          if (friend.friendId === friendId) {
            friend.isActive = isActive;
          }
        });
      }
    });
  },

  // 更新好友备注
  UPDATE_FRIEND_REMARK(state, { friendId, remark }) {
    state.friends.forEach(group => {
      if (group.friendshipsDTOS) {
        group.friendshipsDTOS.forEach(friend => {
          if (friend.friendId === friendId) {
            friend.remark = remark;
          }
        });
      }
    });
  },

  // 更新好友星标状态
  UPDATE_FRIEND_STAR(state, { friendId, isStar }) {
    state.friends.forEach(group => {
      if (group.friendshipsDTOS) {
        group.friendshipsDTOS.forEach(friend => {
          if (friend.friendId === friendId) {
            friend.isStar = isStar;
          }
        });
      }
    });
  },

  // 从所有分组中删除好友
  REMOVE_FRIEND_FROM_GROUPS(state, friendId) {
    state.friends.forEach(group => {
      if (group.friendshipsDTOS) {
        const index = group.friendshipsDTOS.findIndex(friend => 
          friend.friendId === friendId
        );
        if (index !== -1) {
          group.friendshipsDTOS.splice(index, 1);
        }
      }
    });
  },

  REMOVE_FRIEND(state, id) {
    state.friends = state.friends.filter((friend) => friend.id !== id);
    // 清理相关设置
    state.pinnedFriends = state.pinnedFriends.filter(
      (friendId) => friendId !== id
    );
    delete state.onlineStatus[id];
    delete state.muteSettings[id];
  },

  SET_GROUPS(state, groups) {
    state.groups = groups;
  },

  SET_SEARCH_KEYWORD(state, keyword) {
    state.searchKeyword = keyword;
  },

  SET_CURRENT(state, id) {
    state.currentId = id;
  },

  // 在线状态
  UPDATE_ONLINE_STATUS(state, { id, status, lastSeen }) {
    state.onlineStatus[id] = { status, lastSeen };
  },

  // 好友请求
  ADD_FRIEND_REQUEST(state, { type, request }) {
    if (type === "sent") {
      state.friendRequests.sent.push(request);
    } else if (type === "received") {
      state.friendRequests.received.push(request);
    }
  },

  REMOVE_FRIEND_REQUEST(state, { type, id }) {
    if (type === "sent") {
      state.friendRequests.sent = state.friendRequests.sent.filter(
        (req) => req.id !== id
      );
    } else if (type === "received") {
      state.friendRequests.received = state.friendRequests.received.filter(
        (req) => req.id !== id
      );
    }
  },

  // 黑名单
  ADD_TO_BLACKLIST(state, user) {
    state.blacklist.push(user);
  },

  REMOVE_FROM_BLACKLIST(state, id) {
    state.blacklist = state.blacklist.filter((user) => user.id !== id);
  },

  // 置顶操作
  PIN_FRIEND(state, id) {
    if (!state.pinnedFriends.includes(id)) {
      state.pinnedFriends.push(id);
    }
  },

  UNPIN_FRIEND(state, id) {
    state.pinnedFriends = state.pinnedFriends.filter(
      (friendId) => friendId !== id
    );
  },

  // 免打扰操作
  MUTE_FRIEND(state, { id, muteUntil }) {
    state.muteSettings[id] = {
      isMuted: true,
      muteUntil: muteUntil || null,
      muteTime: Date.now(),
    };
  },

  UNMUTE_FRIEND(state, id) {
    delete state.muteSettings[id];
  },

  // 排序设置
  SET_SORT_BY(state, sortBy) {
    state.sortBy = sortBy;
  },

  SET_SORT_ORDER(state, order) {
    state.sortOrder = order;
  },

  // 过滤设置
  SET_FILTER_TYPE(state, type) {
    state.filterType = type;
  },
};

const actions = {
  // 加载好友列表
  async loadFriends({ commit }) {

    commit("SET_LOADING", true);
    
    try {
      // 从服务器加载好友列表（不分页，获取全部数据）
      const res = await service({
        method: "get",
        url: "friend/list"
        // 移除分页参数，直接获取全部好友数据
      });
      
      if (res && res.data) {
        // 转换数据格式以适配现有逻辑
        const friendsData = res.data.map(friend => ({
          id: friend.friendId,
          name: friend.remarkName || friend.friendNickname,
          nickname: friend.friendNickname,
          avatar: friend.friendAvatar,
          status: friend.friendStatus,
          isOnline: friend.isOnline === 1,
          groupName: friend.groupName,
          createTime: friend.createTimeStr,
          isTop: friend.isTop,
          unreadCount: friend.unreadCount,
          labelList: friend.labelList
        }));
        
        commit("SET_FRIENDS", friendsData || []);

      }
    } catch (error) {
      console.error("加载好友列表失败:", error);
      throw error;
    } finally {
      commit("SET_LOADING", false);
    }
  },

  // 加载群组列表
  async loadGroups({ commit }) {

    commit("SET_LOADING", true);
    
    try {
      // 从服务器加载群组列表（不分页，获取全部数据）
      const res = await service({
        method: "get",
        url: "groups/list"
        // 移除分页参数，直接获取全部群组数据
      });
      
      if (res && res.data) {
        // 转换数据格式以适配现有逻辑
        const groupsData = res.data.map(group => ({
          id: group.groupId || group.id,
          name: group.remarkName || group.groupName || group.name,
          groupName: group.groupName || group.name,
          displayName: group.remarkName || group.groupName || group.name,
          avatar: group.groupAvatar || group.avatar,
          groupAvatar: group.groupAvatar || group.avatar,
          status: group.status,
          memberCount: group.currentMemberCount || group.memberCount || group.groupChatCount || 0,
          groupChatCount: group.currentMemberCount || group.memberCount || group.groupChatCount || 0,
          createTime: group.createTimeStr || group.createTime,
          isOnline: group.isOnline || 1,
          isTop: group.isTop || 0,
          unreadCount: group.unreadCount || 0
        }));
        
        commit("SET_GROUPS", groupsData || []);

      }
    } catch (error) {
      console.error("加载群组列表失败:", error);
      throw error;
    } finally {
      commit("SET_LOADING", false);
    }
  },

  // 加载所有联系人（好友+群组）
  async loadAllContacts({ dispatch, commit }) {

    commit("SET_LOADING", true);
    
    try {
      // 并行加载好友和群组（不分页，获取全部数据）
      const [friendsRes, groupsRes] = await Promise.all([
        service({
          method: "get",
          url: "friend/list"
          // 移除分页参数，直接获取全部好友数据
        }),
        service({
          method: "get", 
          url: "groups/list"
          // 移除分页参数，直接获取全部群组数据
        })
      ]);
      
      // 转换好友数据格式
      let friendsData = [];
      if (friendsRes && friendsRes.data) {
        friendsData = friendsRes.data.map(friend => ({
          id: friend.friendId,
          name: friend.remarkName || friend.friendNickname,
          nickname: friend.friendNickname,
          avatar: friend.friendAvatar,
          status: friend.friendStatus,
          isOnline: friend.isOnline === 1,
          groupName: friend.groupName,
          createTime: friend.createTimeStr,
          isTop: friend.isTop,
          unreadCount: friend.unreadCount,
          labelList: friend.labelList
        }));
        commit("SET_FRIENDS", friendsData);

      }
      
      // 转换群组数据格式
      let groupsData = [];
      if (groupsRes && groupsRes.data) {
        groupsData = groupsRes.data.map(group => ({
          id: group.groupId || group.id,
          name: group.remarkName || group.groupName || group.name,
          groupName: group.groupName || group.name,
          displayName: group.remarkName || group.groupName || group.name,
          avatar: group.groupAvatar || group.avatar,
          groupAvatar: group.groupAvatar || group.avatar,
          status: group.status,
          memberCount: group.currentMemberCount || group.memberCount || group.groupChatCount || 0,
          groupChatCount: group.currentMemberCount || group.memberCount || group.groupChatCount || 0,
          createTime: group.createTimeStr || group.createTime,
          isOnline: group.isOnline || 1,
          isTop: group.isTop || 0,
          unreadCount: group.unreadCount || 0
        }));
        commit("SET_GROUPS", groupsData);

      }
      
      // 更新统计信息
      commit("SET_STATISTICS", {
        totalFriends: friendsData.length,
        totalGroups: groupsData.length,
        onlineFriends: friendsData.filter(f => f.isOnline).length,
        activeGroups: groupsData.filter(g => g.status === 0).length
      });
      
    } catch (error) {
      console.error("加载联系人失败:", error);
      throw error;
    } finally {
      commit("SET_LOADING", false);
    }
  },
  
  // 初始化联系人模块
  async initialize({ commit, state }) {

    // 防止重复初始化
    if (state.loading) {

      return;
    }
    
    commit("SET_LOADING", true);

    try {
      // 检查缓存
      const cachedData = localStorage.getItem("contactList_cache");
      if (cachedData) {
        const { data, timestamp } = JSON.parse(cachedData);
        if (Date.now() - timestamp < 5 * 60 * 1000) {
          commit("SET_FRIENDS", data.friends || []);
          commit("SET_GROUPS", data.groups || []);

          return;
        } else {

        }
      }

      // 从服务器加载（这里需要您提供对应的API）
      // const [friends, groups] = await Promise.all([
      //   api.getFriends(),
      //   api.getFriendGroups()
      // ])

      // 从服务器加载好友列表
      let friendMenu = [];
      try {
        const res = await service({
          method: "get",
          url: "users/get/friendships/3",
          params: {
            remark: null,
            username: null,
          },
        });
        
        if (res && res.code === 200) {
          friendMenu = res.data || [];
          commit("SET_FRIENDS", friendMenu);
          commit("SET_GROUPS", []);
          // 联系人列表加载成功
        } else {
          console.warn("contactList API响应异常:", res);
          commit("SET_FRIENDS", []);
          commit("SET_GROUPS", []);
        }
      } catch (apiError) {
        console.error("contactList API请求失败:", apiError);
        // API请求失败时，尝试使用备用接口或返回空数据
        commit("SET_FRIENDS", []);
        commit("SET_GROUPS", []);
        throw apiError; // 重新抛出错误，让上层处理
      }

      // 缓存数据
      localStorage.setItem(
        "contactList_cache",
        JSON.stringify({
          data: { friends: friendMenu, groups: [] },
          timestamp: Date.now(),
        })
      );

    } catch (error) {
      console.error("contactList 模块初始化失败:", error);

      // 尝试使用缓存数据
      const cachedData = localStorage.getItem("contactList_cache");
      if (cachedData) {
        try {
          const { data } = JSON.parse(cachedData);
          commit("SET_FRIENDS", data.friends || []);
          commit("SET_GROUPS", data.groups || []);
          console.warn("contactList 使用缓存数据作为备用");
        } catch (parseError) {
          console.error("contactList 缓存数据解析失败:", parseError);
          commit("SET_FRIENDS", []);
          commit("SET_GROUPS", []);
        }
      } else {
        commit("SET_FRIENDS", []);
        commit("SET_GROUPS", []);
        console.warn("contactList 使用默认空数据");
      }
    } finally {
      commit("SET_LOADING", false);
    }
  },

  // 加载联系人（保持向后兼容）
  async loadContacts({ dispatch }) {
    return dispatch("initialize");
  },

  async addFriend({ commit }, friendData) {
    try {
      // 这里需要您提供对应的API
      // const newFriend = await api.addFriend(friendData)
      // commit('ADD_FRIEND', newFriend)
      // return newFriend

      // 临时实现
      const newFriend = {
        id: Date.now(),
        ...friendData,
        createdAt: new Date().toISOString(),
        onlineStatus: "offline",
        lastActiveTime: new Date().toISOString(),
      };

      commit("ADD_FRIEND", newFriend);

      return newFriend;
    } catch (error) {
      console.error("添加好友失败:", error);
      throw error;
    }
  },

  async deleteFriend({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.deleteFriend(id)
      commit("REMOVE_FRIEND", id);
    } catch (error) {
      console.error("删除好友失败:", error);
    }
  },

  // 好友请求
  async sendFriendRequest({ commit }, { userId, message }) {
    try {
      // 这里需要您提供对应的API
      // const request = await api.sendFriendRequest(userId, message)
      // commit('ADD_FRIEND_REQUEST', { type: 'sent', request })

      // 临时实现
      const request = { id: Date.now(), userId, message };
      commit("ADD_FRIEND_REQUEST", { type: "sent", request });
    } catch (error) {
      console.error("发送好友请求失败:", error);
    }
  },

  async acceptFriendRequest({ commit }, requestId) {
    try {
      // 这里需要您提供对应的API
      // const friend = await api.acceptFriendRequest(requestId)
      // commit('ADD_FRIEND', friend)
      // commit('REMOVE_FRIEND_REQUEST', { type: 'received', id: requestId })

      // 临时实现
      const friend = { id: Date.now(), name: "新好友" };
      commit("ADD_FRIEND", friend);
      commit("REMOVE_FRIEND_REQUEST", { type: "received", id: requestId });
    } catch (error) {
      console.error("接受好友请求失败:", error);
    }
  },

  async rejectFriendRequest({ commit }, requestId) {
    try {
      // 这里需要您提供对应的API
      // await api.rejectFriendRequest(requestId)
      commit("REMOVE_FRIEND_REQUEST", { type: "received", id: requestId });
    } catch (error) {
      console.error("拒绝好友请求失败:", error);
    }
  },

  // 黑名单
  async addToBlacklist({ commit }, user) {
    try {
      // 这里需要您提供对应的API
      // await api.addToBlacklist(user.id)
      commit("ADD_TO_BLACKLIST", user);
    } catch (error) {
      console.error("添加到黑名单失败:", error);
    }
  },

  async removeFromBlacklist({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.removeFromBlacklist(id)
      commit("REMOVE_FROM_BLACKLIST", id);
    } catch (error) {
      console.error("从黑名单移除失败:", error);
    }
  },

  // 置顶操作
  async pinFriend({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.pinFriend(id)
      commit("PIN_FRIEND", id);
    } catch (error) {
      console.error("置顶好友失败:", error);
    }
  },

  async unpinFriend({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.unpinFriend(id)
      commit("UNPIN_FRIEND", id);
    } catch (error) {
      console.error("取消置顶失败:", error);
    }
  },

  // 免打扰操作
  async muteFriend({ commit }, { id, muteUntil }) {
    try {
      // 这里需要您提供对应的API
      // await api.muteFriend(id, muteUntil)
      commit("MUTE_FRIEND", { id, muteUntil });
    } catch (error) {
      console.error("设置免打扰失败:", error);
    }
  },

  async unmuteFriend({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.unmuteFriend(id)
      commit("UNMUTE_FRIEND", id);
    } catch (error) {
      console.error("取消免打扰失败:", error);
    }
  },

  // 更新好友在线状态
  updateFriendStatus({ commit }, { friendId, isActive }) {
    commit("UPDATE_FRIEND_STATUS", { friendId, isActive });
  },

  // 更新好友备注
  updateFriendRemark({ commit }, { friendId, remark }) {
    commit("UPDATE_FRIEND_REMARK", { friendId, remark });
  },

  // 更新好友星标状态
  updateFriendStar({ commit }, { friendId, isStar }) {
    commit("UPDATE_FRIEND_STAR", { friendId, isStar });
  },

  // 删除好友
  removeFriend({ commit }, friendId) {
    // 从所有分组中删除指定好友
    commit("REMOVE_FRIEND_FROM_GROUPS", friendId);
  },
};

const getters = {
  // 当前好友
  currentFriend: (state) => {
    return state.friends.find((friend) => friend.id === state.currentId);
  },

  // 在线好友
  onlineFriends: (state) => {
    return state.friends.filter(
      (friend) => state.onlineStatus[friend.id]?.status === "online"
    );
  },

  // 离线好友
  offlineFriends: (state) => {
    return state.friends.filter(
      (friend) => state.onlineStatus[friend.id]?.status === "offline"
    );
  },

  // 置顶好友
  pinnedFriends: (state) => {
    return state.friends.filter((friend) =>
      state.pinnedFriends.includes(friend.id)
    );
  },

  // 免打扰好友
  mutedFriends: (state) => {
    return state.friends.filter(
      (friend) => state.muteSettings[friend.id]?.isMuted
    );
  },

  // 过滤后的好友列表
  filteredFriends: (state) => {
    let friends = state.friends;

    // 按类型过滤
    switch (state.filterType) {
      case "online":
        friends = friends.filter(
          (friend) => friend.id && state.onlineStatus[friend.id]?.status === "online"
        );
        break;
      case "offline":
        friends = friends.filter(
          (friend) => friend.id && state.onlineStatus[friend.id]?.status === "offline"
        );
        break;
      case "blocked":
        friends = state.blacklist;
        break;
    }

    // 按搜索关键词过滤
    if (state.searchKeyword) {
      const keyword = state.searchKeyword.toLowerCase();
      friends = friends.filter(
        (friend) =>
          friend.name.toLowerCase().includes(keyword) ||
          friend.nickname?.toLowerCase().includes(keyword)
      );
    }

    // 排序
    friends.sort((a, b) => {
      let aValue, bValue;

      switch (state.sortBy) {
        case "name":
          aValue = a.nickname || a.name;
          bValue = b.nickname || b.name;
          break;
        case "onlineStatus":
          aValue = (a.id && state.onlineStatus[a.id]?.status === "online") ? 1 : 0;
          bValue = (b.id && state.onlineStatus[b.id]?.status === "online") ? 1 : 0;
          break;
        case "lastSeen":
          aValue = (a.id && state.onlineStatus[a.id]?.lastSeen) || 0;
          bValue = (b.id && state.onlineStatus[b.id]?.lastSeen) || 0;
          break;
      }

      if (state.sortOrder === "asc") {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    // 置顶好友放在最前面
    const pinned = friends.filter((friend) =>
      friend.id && state.pinnedFriends.includes(friend.id)
    );
    const unpinned = friends.filter(
      (friend) => !friend.id || !state.pinnedFriends.includes(friend.id)
    );

    return [...pinned, ...unpinned];
  },

  // 过滤后的群组列表
  filteredGroups: (state) => {
    let groups = state.groups;

    // 按类型过滤
    switch (state.filterType) {
      case "active":
        groups = groups.filter((group) => group.isActive === 1);
        break;
      case "inactive":
        groups = groups.filter((group) => group.isActive === 0);
        break;
    }

    // 按搜索关键词过滤
    if (state.searchKeyword) {
      const keyword = state.searchKeyword.toLowerCase();
      groups = groups.filter(
        (group) =>
          group.groupName.toLowerCase().includes(keyword) ||
          group.groupDescription?.toLowerCase().includes(keyword)
      );
    }

    // 排序
    groups.sort((a, b) => {
      let aValue, bValue;

      switch (state.sortBy) {
        case "name":
          aValue = a.groupName;
          bValue = b.groupName;
          break;
        case "memberCount":
          aValue = a.memberCount || 0;
          bValue = b.memberCount || 0;
          break;
        case "lastActiveTime":
          aValue = new Date(a.lastActiveTime || 0).getTime();
          bValue = new Date(b.lastActiveTime || 0).getTime();
          break;
      }

      if (state.sortOrder === "asc") {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    // 置顶群组放在最前面
    const pinned = groups.filter((group) =>
      state.pinnedGroups.includes(group.id)
    );
    const unpinned = groups.filter(
      (group) => !state.pinnedGroups.includes(group.id)
    );

    return [...pinned, ...unpinned];
  },

  // 合并的联系人列表（用于统一显示）
  allContacts: (state) => {
    const friends = state.friends.map(friend => ({
      ...friend,
      type: 'friend',
      displayName: friend.displayName || friend.remark,
      avatar: friend.avatar
    }));
    
    const groups = state.groups.map(group => ({
      ...group,
      type: 'group',
      displayName: group.groupName,
      avatar: group.groupAvatar,
      memberCount: group.memberCount
    }));
    
    return [...friends, ...groups];
  },

  // 按分组组织的好友
  friendsByGroup: (state) => {
    const result = {};

    // 初始化分组
    state.groups.forEach((group) => {
      result[group.id] = {
        ...group,
        friends: [],
      };
    });

    // 添加好友到对应分组
    state.friends.forEach((friend) => {
      const groupId = friend.groupId || "default";
      if (!result[groupId]) {
        result[groupId] = {
          id: groupId,
          name: "默认分组",
          friends: [],
        };
      }
      result[groupId].friends.push(friend);
    });

    return result;
  },

  // 待处理的好友请求
  pendingRequests: (state) => {
    return state.friendRequests.received;
  },

  // 免打扰状态
  isMuted: (state) => (id) => {
    const setting = state.muteSettings[id];
    if (!setting) return false;

    if (setting.muteUntil && Date.now() > setting.muteUntil) {
      return false;
    }

    return setting.isMuted;
  },

  // 置顶状态
  isPinned: (state) => (id) => {
    return state.pinnedFriends.includes(id);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
